package pers.yurwisher.rubick.common.service;

import cn.hutool.core.util.ArrayUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import pers.yurwisher.rubick.common.constant.CacheConstant;
import pers.yurwisher.rubick.common.user.CurrentUser;
import pers.yurwisher.rubick.common.user.CustomUserDetails;
import pers.yurwisher.rubick.common.utils.PudgeUtil;

import java.util.stream.Stream;

/**
 * @author yq
 * @date 2021年4月23日 10:28:28
 * @description 全局自定义权限校验 自动给admin放行
 * @since V1.0.0
 */
@Service(value = "el")
@Slf4j
public class ElPermissionService {

    private final CustomRedisCacheService customRedisCacheService;

    public ElPermissionService(CustomRedisCacheService customRedisCacheService) {
        this.customRedisCacheService = customRedisCacheService;
        log.info("auto inject ElPermissionService");
    }

    public Boolean check(String... permissions) {
        CurrentUser currentUser = CustomUserDetails.current();
        if (currentUser.isAdmin()) {
            return true;
        } else {
            //未配置 permission标识
            if (ArrayUtil.isEmpty(permissions)) {
                return false;
            } else {
                String hashKey = PudgeUtil.generateKeyWithDoubleColon(CacheConstant.Hashs.SYSTEM_USER_PERMISSION, currentUser.getId().toString());
                return Stream.of(permissions).anyMatch(s -> customRedisCacheService.hExists(hashKey, s));
            }
        }
    }
}
